<template>
	<view class="TagsPopup">
		<u-popup :show="show" :round="20" mode="bottom" @close="finish()" bgColor="#fff">
			<view class="popup_box">
				<view class="u-sticky">
					<view class="top_btn">
						<view class="tags-popup-btn"><u-button text="取消" @click="close()"></u-button></view>
						<view class="tags-popup-btn">
							<u-button type="primary" text="完成" @click="finish()"></u-button>
						</view>
					</view>

					<view class="popup_tag_box">
						<view class="popup_tag" v-for="(item, index) in tags" :key="item.id">
							<!-- <u-tag
								:text="item.name"
								bgColor="#55acee"
								borderColor="#55acee"
								@click="clickTag(item, index)"
							></u-tag> -->
							<Tag :text="item.name" @click="clickTag(item, index)"></Tag>
						</view>
					</view>

					<view class="search_tag" v-if="hasSearch">
						<u-search
							v-model="keyword"
							inputAlign="left"
							bgColor="#fff"
							placeholderColor="#cfcfd2"
							shape="square"
							:showAction="false"
							height="80"
							placeholder="新增或搜索标签"
							@input="search"
						></u-search>
					</view>
				</view>

				<view :class="['popup_tag_list', hasSearch ? '' : 'popup_height']" :style="{'--hasSearch': hasSearch}" v-show="!keyword">
					<uni-indexed-list
						:options="list"
						:showSelect="true"
						:select="select"
						@click="selectTag()"
					></uni-indexed-list>
				</view>

				<view class="search_result" v-show="keyword">
					<view class="gap" style="height: 60rpx;">搜索结果</view>
					<view class="search_list">
						<ListItem v-if="!searchResults.length" :title="`新增 “${keyword}” 标签`" @click="createTag" />
						<ListItem
							v-for="(item, index) in searchResults"
							:key="index"
							:title="item.name"
							@click="selectSearchTag(item)"
						/>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import api from '@/common/api.js';
import ListItem from './ListItem.vue';
import { initial } from '@/common/chineseConversion.js';
import Tag from '@/components/Tag/Tag.vue';
export default {
	name: 'TagsPopup',
	components: {
		ListItem,
		Tag
	},
	props: {
		show: {
			type: Boolean,
			default: false
		},
		chooses: {
			type: Array,
			default() {
				return [];
			}
		},
		options: {
			type: Array,
			default() {
				return [];
			}
		},
		hasSearch: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			tags: [],
			list: [],
			keyword: '',
			searchResult: [],
			select: [],
			timeout: null,
			searchResults: [],
		};
	},
	watch: {
		chooses: {
			handler(newVal, oldVal) {
				console.log('已选标签有变化');
				this.pySort(this.options, this.chooses);
			}
		}
	},
	mounted() {
		console.log('mounted');
		this.pySort(this.options, this.chooses);
	},
	methods: {
		pySort(arrList, chooses) {
			let letterList = [];
			let choosesNames = chooses.map(v => {
				return v.name;
			});
			arrList.forEach(item => {
				let letter = initial(item.name).toUpperCase();
				let index = letterList.indexOf(letter);
				let checked = choosesNames.includes(item.name);
				// console.log("checked ==>", checked);
				if (index === -1) {
					letterList.push(letter);
					let obj = {
						letter: '',
						data: []
					};
					obj.letter = letter;
					obj.data.push({
						name: item.name,
						id: item.id,
						checked
					});
					this.list.push(obj);
				} else {
					this.list[index].data.push({
						name: item.name,
						id: item.id,
						checked
					});
				}
			});
			this.list.sort((a, b) => {
				return a.letter.charCodeAt(0) - b.letter.charCodeAt(0);
			});
			console.log('this.list ==>', this.list);

			if (chooses.length) {
				this.tags = chooses;
				// this.list.forEach((value, index) => {
				// 	if (value.data.length === 0) {
				// 		return
				// 	}
				// 	value.data.forEach(item => {
				// 		if (item.checked) {
				// 			this.tags.push(item.name);
				// 			console.log("item.name ==>", item.name);
				// 		}
				// 	})
				// })
			}
		},

		// 搜索
		search() {
			console.log('keyword ==>', this.keyword);
			clearTimeout(this.timeout);
			this.timeout = null;
			this.timeout = setTimeout(() => {
				this.getTags();
			}, 500);
		},

		// 获取所有标签
		async getTags() {
			if (!this.keyword) {
				return false;
			}
			try {
				let res = await this.$ajax({
					url: api.tags,
					data: {
						_keyword: this.keyword
					}
				});
				console.log('resTags ==>', res);
				let data = res.data.data;
				this.searchResults = data.asset_tags;
				console.log('searchResults ==>', this.searchResults);
			} catch (e) {
				console.log(e);
			}
		},

		// 选择标签
		selectTag(obj) {
			console.log('selectTag ==>', obj);
			this.select = obj.select.map(v => v.name);
			let item = obj.item;
			let tags = this.tags.map(v => v.name);
			let index = tags.indexOf(item.name);
			if (index === -1) {
				this.tags.push({ id: item.id ? item.id : item.itemIndex, name: item.name });
			} else {
				if (item.checked) {
					this.tags.splice(index, 1);
				}
			}
		},

		// 点击标签
		clickTag(item, index) {
			this.tags.splice(index, 1);
			this.select = this.tags.map(v => v.name);
		},
		
		// 选择搜索结果标签
		selectSearchTag(item) {
			let tags = this.tags.map(v => v.name);
			let index = tags.indexOf(item.name);
			if (index === -1) {
				this.tags.push({ name: item.name });
				this.select = this.tags.map(v => v.name);
			}
			this.keyword = '';
		},
		
		// 新增标签
		createTag() {
			let tags = this.tags.map(v => v.name);
			let index = tags.indexOf(this.keyword);
			if (index === -1) {
				this.tags.push({ name: this.keyword });
			}
		},

		close() {
			this.$emit('close');
		},

		finish() {
			this.$emit('finish', this.tags);
		}
	}
};
</script>

<style lang="scss">
.TagsPopup {
	.popup_box {
		// position: relative;
		// z-index: 10000;
		height: 90vh;
	}

	.top_btn {
		display: flex;
		justify-content: space-between;
		padding: 30rpx;
		background-color: #ededed;
		border-radius: 20rpx 20rpx 0 0;
		z-index: 999;
	}

	.btn {
		display: inline-block;
	}

	.popup_tag_box {
		padding: 20rpx 30rpx;
		border-bottom: 1px solid rgba($color: #eceef0, $alpha: 1);
		height: 174rpx;
		overflow: auto;
	}

	.popup_tag {
		display: inline-block;
		margin: 0 20rpx 10rpx 0;
	}

	.popup_tag_list {
		position: absolute;
		left: 0;
		bottom: 0;
		width: 100%;
		z-index: 9999;
		height: calc(100% - 420rpx);
		// @if var(--hasSearch) == true {
		// 	height: calc(100% - 420rpx);
		// } @else {
		// 	height: calc(100% - 336rpx);
		// }
	}
	
	.popup_height {
		height: calc(100% - 336rpx) !important;
	}

	.gap {
		height: 60rpx;
		padding: 0 30rpx;
		box-sizing: border-box;
		font-size: 24rpx;
		line-height: 60rpx;
		color: #a2a3a5;
		background-color: #f7f8fa;
	}

	.search_list {
		padding: 0 32rpx;
	}
}
</style>
